﻿#region

using System;
using System.Configuration;
using Autofac;
using HouseHoldBudget.Core.Configuration;
using HouseHoldBudget.Core.Infrastructure.DependencyManagement;

#endregion

namespace HouseHoldBudget.Core.Infrastructure
{
    public class DependencyEngine : IEngine
    {
        #region Fields

        private ContainerManager _containerManager;

        #endregion

        #region Constructors

        /// <summary>
        ///   Creates an instance of the content engine using default settings and configuration.
        /// </summary>
        public DependencyEngine()
            : this(EventBroker.Instance, new ContainerConfigurer())
        {
        }

        public DependencyEngine(EventBroker broker, ContainerConfigurer configurer)
        {
            var config = ConfigurationManager.GetSection("HouseHoldBudgetConfig") as HouseHoldBudgetConfig;
            InitializeContainer(configurer, broker, config);
        }

        #endregion

        #region Instance Methods

        private void InitializeContainer(ContainerConfigurer configurer, EventBroker broker, HouseHoldBudgetConfig config)
        {
            var builder = new ContainerBuilder();

            _containerManager = new ContainerManager(builder.Build());
            configurer.Configure(this, _containerManager, broker, config);
        }

        #endregion

        #region IEngine Members

        /// <summary>
        ///   Initialize components and plugins in the nop environment.
        /// </summary>
        /// <param name="config"> Config </param>
        public void Initialize(HouseHoldBudgetConfig config)
        {
        }

        public T Resolve<T>() where T : class
        {
            return ContainerManager.Resolve<T>();
        }

        public object Resolve(Type type)
        {
            return ContainerManager.Resolve(type);
        }

        public T[] ResolveAll<T>()
        {
            return ContainerManager.ResolveAll<T>();
        }

        public ContainerManager ContainerManager
        {
            get
            {
                return _containerManager;
            }
        }

        #endregion
    }
}